import React, { createContext, useContext, useState, useEffect } from 'react';
import { getUserProfile } from '../services/messageService';
import { dbService } from '../services/dbService';

const UserContext = createContext();

export const UserProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(() => {
    return { id: '', name: '', avatar: '' };
  });

  const [contacts, setContacts] = useState(() => {
    return {};
  });

  const updateContacts = async (newContacts) => {
    setContacts(newContacts);
    // 将联系人列表作为单个对象存储，使用固定键名'contacts'
    await dbService.set(dbService.getStoreNames().CONTACTS, { id: 'contacts', data: newContacts });
  };

  const fetchUserProfile = async () => {
    try {
      const userData = await getUserProfile();
      setCurrentUser(userData);
      // 确保用户数据以'currentUser'为id存储，以便后续检索
      await dbService.set(dbService.getStoreNames().USER, { ...userData, id: 'currentUser' });
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
  };

  useEffect(() => {
    const initData = async () => {
      const storeNames = dbService.getStoreNames();
      const user = await dbService.get(storeNames.USER, 'currentUser');
      const contactsRecord = await dbService.get(storeNames.CONTACTS, 'contacts');
      
      if (user) setCurrentUser(user);
      if (contactsRecord && contactsRecord.data) {
        setContacts(contactsRecord.data);
      }
      
      if (!user?.id) {
        fetchUserProfile();
      }
    };
    
    initData();
  }, []);
  
  // 确保用户信息变更时重新获取数据
  useEffect(() => {
    if (currentUser.id) {
      // 用户已登录，可以执行其他初始化操作
    }
  }, [currentUser.id]);

  return (
    <UserContext.Provider value={{ 
      currentUser, 
      setCurrentUser,
      contacts,
      updateContacts 
    }}>
      {children}
    </UserContext.Provider>
  );
};

export const useUser = () => {
  return useContext(UserContext);
};